<script setup lang="ts">
import { onMounted, reactive, ref, watch, computed } from 'vue';
import API from '@/services';
import { useStore } from '@/store';
import { Message } from '@arco-design/web-vue';
import _ from 'lodash';

const store = useStore();
const emit = defineEmits(['sureDimension', 'cancelDimension']);
const fieldList = computed(() => store.state.model.tableFieldList);

// 获取关联维度列表
const dimensionList = ref<any>();
const getDimensionList = async (cnName?: string) => {
  dimensionList.value = [];
  try {
    const { code, data } = await API.dimension.getDimensionHintName({
      cnName
    });
    if (code === 200 && Array.isArray(data)) {
      // dimensionList.value = data;
      dimensionList.value =
        data?.map((d) => {
          return {
            label: `${d.cnName}`,
            value: `${d.id}`
          };
        }) || [];
    }
  } catch (error) {
    console.log(error);
  }
};

const props = defineProps({
  nowBindItem: {
    type: Object
  },
  isRevise: {
    type: Boolean,
    default: false
  },
  visible: {
    type: Boolean,
    default: false
  }
});
const visibleVal = computed(() => props.visible);
const modalVisible = ref(false);
watch(visibleVal, (newVal, oldVal) => {
  console.log(newVal, '每次传来的值');
  modalVisible.value = newVal;
});

const isEdit = computed(() => props.isRevise);
const nowBindItemVal = computed(() => props.nowBindItem);
const formLinkRef = ref();
const formLinkData = reactive({
  tableFieldColumn: '', // 维度ID
  tableFieldName: '', // 维度名称
  dimensionId: '', // 绑定维度的id
  dimensionName: '', // 绑定维度的name
  ifDistinct: 0 // 是否去重
});
watch(nowBindItemVal, (newVal: any) => {
  if (!isEdit.value) {
    getDimensionList('');
    bindDimensionList.value = [];
    formLinkRef.value.clearValidate();
    formLinkRef.value.resetFields();
    formLinkData.tableFieldColumn = newVal.tableFieldName;
  } else {
    Object.keys(newVal).forEach((key) => {
      formLinkData[key] = newVal[key];
    });
  }
});
const tableFieldColumnOptions = computed(() => {
  return fieldList.value?.filter(
    (item: any) =>
      item.tableFieldName !== formLinkData.tableFieldName &&
      item.relationType === 0
  );
});
const bindDimensionList = ref<any>([]);
// 关闭弹窗之前
const onBeforeOk = async (done: any) => {
  const err = await formLinkRef.value.validate();
  if (!err) {
    done(true);
  } else {
    done(false);
  }
};
const handleSureLink = async () => {
  let arr = store.state.model.bindDimensionList;
  let flag = arr.some(
    (item: any) => item.dimensionId === formLinkData.dimensionId
  );
  if (!flag) {
    const copyFormLinkData = _.cloneDeep(formLinkData);
    store.commit('model/changeDimensionList', [copyFormLinkData]);
    // 改变右边div 并连线
    emit('sureDimension', copyFormLinkData);
  } else if (isEdit.value) {
    const copyFormLinkData = _.cloneDeep(formLinkData);
    store.commit('model/updateDimensionList', copyFormLinkData);
    emit('sureDimension', copyFormLinkData);
  } else {
    Message.error('该维度已绑定');
  }
};
const handleCancelLink = () => {
  emit('cancelDimension', false);
  // formLinkRef.value.resetFields();
  // formLinkRef.value.clearValidate();
};

// 选择绑定的维度
const changeBindDimension = (val: any) => {
  formLinkData.dimensionId = val;
  formLinkData.dimensionName = dimensionList.value.find(
    (item: any) => item.value === val
  )?.label;
};

onMounted(() => {});
</script>

<template>
  <!-- 关联维度弹窗 -->
  <a-modal
    :on-before-ok="onBeforeOk"
    @ok="handleSureLink"
    @cancel="handleCancelLink"
    modal-class="bind-dimension-modal"
    v-model:visible="modalVisible"
  >
    <template #title> {{ isEdit ? '修改维度' : '关联维度' }} </template>
    <div class="content">
      <a-form ref="formLinkRef" :model="formLinkData" auto-label-width>
        <a-form-item
          show-colon
          required
          label="维度ID"
          field="tableFieldColumn"
          :rules="[{ required: true, message: '请选择维度ID' }]"
        >
          <a-select
            v-model="formLinkData.tableFieldColumn"
            placeholder="请选择"
          >
            <a-option
              v-for="item of tableFieldColumnOptions"
              :value="item.tableFieldName"
              :label="item.tableFieldName"
              :key="item.id"
            />
          </a-select>
        </a-form-item>

        <a-form-item
          show-colon
          required
          label="维度名"
          field="tableFieldName"
          :rules="[{ required: true, message: '请选择维度名' }]"
        >
          <a-select v-model="formLinkData.tableFieldName" placeholder="请选择">
            <a-option
              v-for="item of fieldList?.filter((item: any) => (item.tableFieldName !== formLinkData.tableFieldColumn) && item.relationType === 0)"
              :value="item.tableFieldName"
              :label="item.tableFieldName"
              :key="item.id"
            />
          </a-select>
        </a-form-item>

        <a-form-item
          show-colon
          required
          label="绑定维度"
          field="dimensionName"
          :rules="[{ required: true, message: '请选择维度' }]"
        >
          <ASelect
            v-model="formLinkData.dimensionName"
            style="width: 100%"
            allow-search
            @search="getDimensionList"
            @change="changeBindDimension"
            allow-clear
            :options="dimensionList"
            placeholder="请输入"
          />
        </a-form-item>

        <a-form-item field="ifDistinct">
          <a-switch
            checked-color="#3C6EFF"
            unchecked-color="#9B9FAB"
            v-model="formLinkData.ifDistinct"
            :checked-value="1"
            :unchecked-value="0"
          />
          <span class="switch-desc">获取数据时去重</span>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<style lang="scss" scoped>
.switch-desc {
  font-size: 14px;
  color: #60646f;
  letter-spacing: 0;
  line-height: 22px;
  font-weight: 400;
  padding-left: 12px;
}
</style>

<style lang="scss">
.bind-dimension-modal {
  .arco-modal-header {
    .arco-modal-title {
      font-size: 16px;
      color: #33353b;
      letter-spacing: 0;
      line-height: 24px;
      font-weight: 600;
    }
  }
}
</style>
